package edu.cuit.avatar.controller;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.util.StringUtils;
import edu.cuit.avatar.entity.Book;
import edu.cuit.avatar.factory.InstanceFactory;
import edu.cuit.avatar.service.BookService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/7/31 17:50
 */
@WebServlet("/book/save")
public class BookSaveServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private BookService service = InstanceFactory.create("book-service");

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        BufferedReader reader = req.getReader();
        String line = null;
        String json = "";
        while( (line = reader.readLine()) != null )
            json += line;

        var result = false;
        if(json.length() > 0){
            var book = JSONObject.parseObject(json, Book.class);
            result = service.save(book) == null ? false : true;
        }

        resp.setContentType("application/json; charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println(JSONObject.toJSONString(result));
    }
}
